package com.xmut.bs.handaccount.activity;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.xmut.bs.handaccount.GlideApp;
import com.xmut.bs.handaccount.R;
import com.xmut.bs.handaccount.adapter.GoodsAdapter;
import com.xmut.bs.handaccount.base.CommonListActivity;
import com.xmut.bs.handaccount.bmob.Goods;
import com.xmut.bs.handaccount.util.DisplayUtils;
import com.xmut.bs.handaccount.util.DividerItemDecoration;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.List;

import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;

import static com.xmut.bs.handaccount.base.Constants.PARAM_GOODS;

/**
 * Description
 * Created by Dollkey on 2018/4/11.
 */

public class GoodsManageActivity extends CommonListActivity<Goods> {

    @Override
    public void beInit() {
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {

            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                if (layoutManager instanceof GridLayoutManager) {// GridLayoutManager
                    // flag如果值是0，相当于这个功能被关闭
                    int dragFlag = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT | ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                    int swipeFlag = 0;
                    // create make
                    return makeMovementFlags(dragFlag, swipeFlag);
                } else if (layoutManager instanceof LinearLayoutManager) {// linearLayoutManager
                    LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
                    int orientation = linearLayoutManager.getOrientation();
                    int dragFlag = 0;
                    int swipeFlag = 0;
                    // 为了方便理解，相当于分为横着的ListView和竖着的ListView
                    if (orientation == LinearLayoutManager.HORIZONTAL) {// 如果是横向的布局
                        swipeFlag = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                        dragFlag = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                    } else if (orientation == LinearLayoutManager.VERTICAL) {// 如果是竖向的布局，相当于ListView
                        dragFlag = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                        swipeFlag = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                    }
                    return makeMovementFlags(dragFlag, swipeFlag);
                }
                return 0;
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public boolean isLongPressDragEnabled() {
                return false;
            }

            @Override
            public boolean isItemViewSwipeEnabled() {
                return super.isItemViewSwipeEnabled();
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                final Goods adv = mComList.get(viewHolder.getAdapterPosition());
                adv.setDelete(true);
                adv.update(new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        if (e == null) {
                            showToast("删除成功");
                            mComList.remove(adv);
                            mAdapter.notifyDataSetChanged();
                        } else {
                            showToast("失败：" + e.getMessage() + "," + e.getErrorCode());
                        }
                    }
                });
            }
        });
        itemTouchHelper.attachToRecyclerView(mRecycleView);
    }

    @Override
    protected String getSubTitle() {
        return "商品管理";
    }

    @Override
    protected RecyclerView.ItemDecoration getItemDecoration() {
        return new DividerItemDecoration(mContext,
                DisplayUtils.dp2px(mContext, 8),
                getResources().getColor(R.color.white));
    }

    @NonNull
    @Override
    protected RecyclerView.LayoutManager getRvLayoutManager() {
        return new LinearLayoutManager(mContext);
    }

    @Override
    protected RecyclerView.Adapter getAdapter(List<Goods> comList) {
        return new GoodsAdapter<Goods>(mContext, comList) {
            @Override
            protected void convert(ViewHolder holder, final Goods goods, int position) {
                holder.getConvertView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent().putExtra(PARAM_GOODS, goods), GoodsDetailActivity.class);
                    }
                });
                holder.setText(R.id.goods_name, goods.getName());
                holder.setText(R.id.goods_note, goods.getDescription());
                holder.setText(R.id.price, "￥".concat(String.valueOf(goods.getPrice())));
                ImageView view = holder.getView(R.id.goods_img);
                GlideApp.with(view).load(goods.getBannerUrls().get(0))
                        .centerCrop()
                        .transform(new MultiTransformation<>(new CenterCrop(), mRoundCornersTransformation))
                        .into(view);
            }
        }.setTypeList(true);
    }

    @Override
    public void getData(int pageNo, int pageSize) {
        mBmobQuery.setSkip(pageNo * pageSize);
        mBmobQuery.setLimit(pageSize);
        mBmobQuery.order("-updatedAt");
        mBmobQuery.addWhereEqualTo("isDelete",false);
        mBmobQuery.findObjects(new FindListener<Goods>() {
            @Override
            public void done(List<Goods> list, BmobException e) {
                if (e == null) {
                    showList(list);
                } else {
                    showError("请求失败：" + e.getMessage());
                }
            }
        });
    }

    @Override
    protected void initParams(Intent intent) {

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_add, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_add:
                startActivityForResult(AddGoodsActivity.class, 1);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                mRefreshLayout.beginRefreshing();
            }
        }
    }
}
